import 'package:get/get.dart';
import 'package:flutter/material.dart';
import '../../../service/xin_he_reqest.dart';
import '../../../utils/xin_he_storage.dart';
import '../../../utils/xin_he_toast.dart';
import '../../shopping_car/models/xin_he_goods_model.dart';
import '../../shopping_car/xin_he_shopping_car/xin_he_shopping_car_logic.dart';
import '../model/xin_he_goods_item_entity.dart';
import 'xin_he_search_state.dart';

class XinHeSearchLogic extends GetxController {
  final XinHeSearchState state = XinHeSearchState();
  final TextEditingController editingController = TextEditingController();


  @override
  void onInit() async{
    // TODO: implement onInit
    super.onInit();

    var list = await XinHeLocalStorage.get(XinHeStorage.searchHistory) ;
    if(list != null && list is List){
      if(list.isNotEmpty){
        state.historyList.value = list;
      }
    }
  }

  void onInputEditCompleteAction() async{

    if(state.inputContent.value.isEmpty) {
      XinHeToast.center('请输入搜索内容');
      return;
    }

    keyboardBack();

    ///历史记录-数据去重
    await _handleHistoryTmpData();

    state.isShowResultPage.value = true;

    await getSearchResult();
  }

  void onInputSubmitAction() {

  }


  /// 回收键盘
  void keyboardBack() {
    if (Get.focusScope?.hasPrimaryFocus == true) {
      Get.focusScope?.unfocus();
    }
  }

  ///输入框输入更改
  void inputChange(String value){
    if(value.isNotEmpty){
      state.isShowDelete.value = true;
    }else {
      state.isShowDelete.value = false;

      state.isShowResultPage.value = false;

    }
    state.inputContent.value = value;

  }

  ///选中
  void onSelectedItem(String content) async {

    ///输入框赋值
    editingController.value = TextEditingValue(
        text: content,
        selection: TextSelection.fromPosition(
            TextPosition(
                affinity: TextAffinity.downstream,
                offset: content.length
            )
        )
    );


    inputChange(content);

    await _handleHistoryTmpData();

    state.isShowResultPage.value = true;

    await getSearchResult();
  }



  ///历史数据去重/写入
  Future _handleHistoryTmpData() async{
    ///历史记录-
    var list = await XinHeLocalStorage.get(XinHeStorage.searchHistory)  ;
    if(list != null ){
      if(list is List){
        List<String>tmp = [];
        if(list.isNotEmpty){
          ///去重
          for(var i in list){
            if(i != state.inputContent.value){
              tmp.add(i);
            }
          }
        }

        tmp.add(state.inputContent.value);
        await XinHeLocalStorage.set(XinHeStorage.searchHistory,tmp);
        state.historyList.value = tmp;
      }
    }else{
      await XinHeLocalStorage.set(XinHeStorage.searchHistory,[state.inputContent.value]);
      state.historyList.value = [state.inputContent.value];
    }
  }


  Future getSearchResult() async {


    requestAllTabData();
  }

  //取消键盘
  void closeKeyboard(){
    if (Get.focusScope?.hasPrimaryFocus == true) {
      Get.focusScope?.unfocus();
    }
  }

  ///清空输入框
  void clearInputContent() {
    editingController.clear();
    inputChange('');

  }

  ///清除历史记录
  void onClearHistory() async {
    await XinHeLocalStorage.remove(XinHeStorage.searchHistory);
    state.historyList.value = [];
  }



  ///添加商品进购物车
  void addGoodsToCartAction(XinHeGoodsModel model){
    XinHeToast.center('已添加');
    final allLogic = Get.find<XinHeShoppingCarLogic>();
    allLogic.state.allItemsList.add(model);

  }


  requestAllTabData()async{
    Map<String,dynamic>map = {
      'name':state.inputContent.value
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/goods/queryGoods',params: map,isPost: false);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }
    List list = result.data['data'] ??[];
    List items = [];
    if(list.isNotEmpty){
      for(var e in list){
        XinHeGoodsItemEntity model = XinHeGoodsItemEntity.fromJson(e);
        // model.iconPath = 'https://xhyp.quexiaoer.cn/upload/goods-photo/goods-photo_20230703074806830_3210.png';

        items.add(model);
      }

      state.resultList.value = items;

    }else {
      state.resultList.clear();

    }

  }

}
